//
//  BlurImageView.swift
//  GoAbroad
//
//  Created by Pink Snow on 2025/5/30.
//

import UIKit
import CoreImage

class BlurImageView: UIImageView {
    
    /// 原始未模糊的图片
    private var originalImage: UIImage?
    
    /// 模糊半径（0 ~ 30 推荐）
    var blurRadius: CGFloat = 0 {
        didSet {
            applyBlur()
        }
    }
    
    /// 设置图片并应用模糊
    func setImage(_ image: UIImage) {
        self.originalImage = image
        applyBlur()
    }
    
    /// 应用模糊效果
    private func applyBlur() {
        guard let originalImage = originalImage else { return }

        // 如果模糊半径为 0，直接显示原图
        guard blurRadius > 0 else {
            self.image = originalImage
            return
        }
        
        // Core Image 模糊处理
        let ciImage = CIImage(image: originalImage)
        let filter = CIFilter(name: "CIGaussianBlur")
        filter?.setValue(ciImage, forKey: kCIInputImageKey)
        filter?.setValue(blurRadius, forKey: kCIInputRadiusKey)
        
        guard let outputImage = filter?.outputImage else { return }

        let context = CIContext()
        let rect = ciImage?.extent ?? CGRect(origin: .zero, size: originalImage.size)

        if let cgImage = context.createCGImage(outputImage, from: rect) {
            self.image = UIImage(cgImage: cgImage)
        }
    }
}
